package com.mapforge.gui.frames.map;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JFrame;

import com.mapforge.collection.WeakReferenceInstanceProvider;
import com.mapforge.listener.TileMapCreationListener;
import com.mapforge.listener.TilesetChangeListener;

/**
 * This class provides a dialog to create new maps. It tracks state which would
 * be lost if the dialog was weakly referenced and collected by the garbage
 * collector, and initializes the dialog when necessary with this state.
 * 
 * @author Will Morrison
 * 
 */
public class NewMapDialogProvider extends
		WeakReferenceInstanceProvider<NewMapDialog> implements ActionListener {
	private JFrame parent;

	/**
	 * Listeners notified whenever a new map is created.
	 */
	private List<TileMapCreationListener> mapCreationListeners;

	/**
	 * Listeners notified after a map is assigned a new Tileset.
	 */
	private List<TilesetChangeListener> tilesetChangeListeners;

	public NewMapDialogProvider(JFrame parent) {
		this.parent = parent;
		mapCreationListeners = new ArrayList<TileMapCreationListener>();
		tilesetChangeListeners = new ArrayList<TilesetChangeListener>();
	}

	public void addTilesetChangeListener(TilesetChangeListener listener) {
		this.tilesetChangeListeners.add(listener);
	}

	public boolean removeTilesetChangeListener(TilesetChangeListener listener) {
		return tilesetChangeListeners.remove(listener);
	}

	public void clearTilesetChangeListeners() {
		tilesetChangeListeners.clear();
	}

	public void addMapCreationListener(TileMapCreationListener listener) {
		this.mapCreationListeners.add(listener);
	}

	public Iterator<TileMapCreationListener> mapCreationListenerIterator() {
		return mapCreationListeners.iterator();
	}

	public Iterator<TilesetChangeListener> tilesetChangeListenersIterator() {
		return tilesetChangeListeners.iterator();
	}

	public void clearMapCreationListeners() {
		mapCreationListeners.clear();
	}

	protected NewMapDialog createNewInstance() {
		NewMapDialog mapDialog = new NewMapDialog(parent, mapCreationListeners,
				tilesetChangeListeners);
		return mapDialog;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		this.getInstance().setVisible(true);
	}
}